package com.jackykeke.kdatabasedemo.db.table

import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.util.Log
import com.jackykeke.kdatabasedemo.FileUtil
import com.jackykeke.kdatabasedemo.R
import com.jackykeke.kdatabasedemo.ZipUtils
import com.jackykeke.kdatabasedemo.db.interfaze.ITable
import com.jackykeke.kdatabasedemo.db.interfaze.ITable.Companion.CREATE_TABLE_SQL
import java.io.*

class GameLibTable : ITable {





    init {
//        var b = StringBuilder()
//        b.append(CREATE_TABLE_SQL + TABLE_NAME)
//        b.append("(" + ID + " INTEGER PRIMARY KEY,")
//        b.append(PACKAGE_NAME_ID + " TEXT)")
//        CREATE_TABLE = b.toString()

    }


    companion object {

        /**
         * 数据库ID<br></br>
         * 值类型: int
         */
        val ID = "_id"

        /**
         * 加密后的包名, 使用md5加密[com.clean.util.MD5Util.md5]<br></br>
         * 值类型: string
         */
        val PACKAGE_NAME_ID = "package_name_id"

        // ============================================================================//
        // ============================================================================//
        /**
         * 表名
         */
        val TABLE_NAME = "game_lib_table"

        /**
         * 创建表
         */
        var CREATE_TABLE: String = StringBuilder().append(CREATE_TABLE_SQL + TABLE_NAME)
            .append("(" + ID + " INTEGER PRIMARY KEY,")
            .append(PACKAGE_NAME_ID + " TEXT)")
            .toString()

        /**
         * 插入默认的游戏库数据, 从raw中读取wy.db的数据插入到当前的数据库表<br>
         *
         * @param context
         * @param db
         */
        fun insertDefaultData(context: Context, db: SQLiteDatabase): Boolean {

            val packageNameIds = loadDefaultGameLibDbFromRaw(context)

            if (packageNameIds.size == 0) return false
            //开启事务
            db.beginTransaction()

            try {
                packageNameIds.forEach { s ->
                    val values = ContentValues()
                    values.put(PACKAGE_NAME_ID, s)
                    db.insert(TABLE_NAME, null, values)
                }
                return true
            } catch (e: Exception) {
                e.printStackTrace();
                return false
            } finally {
                // 能成功多少条数据就多少条
                db.setTransactionSuccessful();
                db.endTransaction();
            }


        }

        private fun loadDefaultGameLibDbFromRaw(context: Context): List<String> {
            val packageNameIds = mutableListOf<String>()
            val cacheDir = context.cacheDir
            val gameLibZip = File(cacheDir, "wy.zip")
            var outputStream: OutputStream? = null
            var inputStream: InputStream? = null
            var query: Cursor? = null

            try {
                //解压 读取
                inputStream = context.resources.openRawResource(R.raw.wy)
                outputStream = FileOutputStream(gameLibZip)
                // 复制一到缓存文件夹后解压
                FileUtil.copy(inputStream, outputStream)
                // 解压到缓存文件夹
                val folder = cacheDir
                val unzip = ZipUtils.unZip(gameLibZip, folder)
                unzip?.let {

                    val db = SQLiteDatabase.openOrCreateDatabase(it, null)

                    query =
                        db.query(TABLE_NAME, arrayOf(PACKAGE_NAME_ID), null, null, null, null, null)



                    query?.let { query ->
                        if (query.moveToFirst()) {
                            do {
                                val columnIndex = query.getColumnIndex(PACKAGE_NAME_ID)
                                val packageNameId = query.getString(columnIndex)
                                packageNameIds.add(packageNameId)
                                Log.d("GameLibTable", "packageNameId:$packageNameId")

                            } while (query.moveToNext())
                        }

                    }
                }


            } catch (e: Exception) {
                e.printStackTrace()
                Log.d("GameLibTable", "失误了 ${e.printStackTrace()}")

            } finally {
                Log.d("GameLibTable", "finally")
                if (null != outputStream) {
                    try {
                        outputStream.close()
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }
                }

                if (null != inputStream) {
                    try {
                        inputStream.close()
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }
                }

                if (null != query) {
                    try {
                        query!!.close()
                    } catch (e: java.lang.Exception) {
                        e.printStackTrace()
                    }
                }
            }
            return packageNameIds
        }
    }

}


















